<template>
  <div class="content-wrap content-container">
    <!-- 标题 -->
    <div class="title-top-box">
      <p class="title">创建需求</p>
    </div>
    <!-- 创建需求 -->
    <div class="create-box" v-loading="loading">
      <el-form class="create-form" ref="ruleCreateFormRef" :rules="createRules" :model="createRequirementForm">
        <!-- 项目名称 -->
        <el-form-item label="项目名称：" required style="width: 50%" prop="projectId">
          <el-select v-model="createRequirementForm.projectId" filterable="true" placeholder="项目名称" fit-input-width
            clearable style="width: 200px">
            <el-option v-for="item in allProjectOptions" :key="item.ID" :label="item.itemName" :value="item.ID" />
          </el-select>
          <el-icon class="add-icon" :size="24" @click="dialogAddProVisible = true">
            <CirclePlus />
          </el-icon>
        </el-form-item>
        <!-- 需求类型 -->
        <el-form-item label="需求类型：" required style="width: 50%;" prop="projectType">
          <el-radio-group v-model="createRequirementForm.projectType">
            <el-radio-button v-for="item in allTypeLists" :key="item.id" :label="item.type" :value="item.id" />
          </el-radio-group>
        </el-form-item>

        <!-- 任务类型 -->
        <el-form-item label="任务类型：" required style="width: 50%;" prop="projectType">
          <el-radio-group v-model="createRequirementForm.taskType">
            <el-radio-button v-for="item in allTaskLists" :key="item.id" :label="item.type" :value="item.id" />
          </el-radio-group>
        </el-form-item>
        <!-- 需求标题 -->
        <el-form-item label="需求标题：" required style="width: 50%" prop="projectTitle">
          <el-input v-model="createRequirementForm.projectTitle" placeholder="请输入需求标题" style="width: 400px"></el-input>
        </el-form-item>
        <!-- 审核人 -->
        <el-form-item v-if="isAuthorityId == '444'" label="审核人：" style="width: 20%;" required
          prop="itemRequirementBossNameUUID">
          <el-select v-model="createRequirementForm.itemRequirementBossNameUUID" placeholder="请选择审核人" filterable
            clearable style="width: 160px; min-width: 100px;">
            <el-option v-for="(item, index) in allRoleUserList" :key="index" :label="item.nickName"
              :value="item.uuid" />
          </el-select>
        </el-form-item>
        <!-- 预计上线时间-有日期限制 -->
        <!--  <el-form-item label="预计上线时间：" prop="onlineTime" style="width: 30%" required>
          <el-date-picker
            style="width: 180px"
            v-model="createRequirementForm.onlineTime"
            type="date"
            placeholder="请选择预计上线日期"
            :disabledDate="disabledDate"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item> -->
        <!-- 预计上线时间-无日期限制 -->
        <el-form-item label="预计上线时间：" prop="onlineTime" style="width: 30%" required>
          <el-date-picker style="width: 180px" v-model="createRequirementForm.onlineTime" type="date"
            placeholder="请选择预计上线日期" format="YYYY/MM/DD" value-format="YYYY-MM-DD" />
        </el-form-item>
        <!-- 需求详情 -->
        <el-form-item label="简述需求：" required style="width: 100%; margin-bottom: 20px;" prop="projectMsg">
          <div style="width: 100%;" v-if="!quickCreateStore.quickCreateData">
            <Toolbar style="height: 41px; border: 1px solid #ddd" :editor="editorRef" :defaultConfig="toolbarConfig" />
            <Editor style="height: 320px; border: 1px solid #ddd; overflow: auto" v-model:modelValue="valueHtml"
              :defaultConfig="editorConfig" @onChange="handleChange" @onCreated="handleCreated" />
          </div>
          <EditorMsgVue v-if="quickCreateStore.quickCreateData" :modelValue="createRequirementForm.projectMsg" @update:modelValue="updateMsg"></EditorMsgVue>
        </el-form-item>
        <!-- 上传文件 -->
        <el-form-item
          v-if="!(isAuthorityId == '555' || isAuthorityId == '666' || isAuthorityId == '777' || isAuthorityId == '111')"
          class="upload-box" label="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;附件:"
          prop="filePaths">
          <div style="width: 100%;">
            <el-button type="primary" size="small" plain @click="openModal = true">
                关联
            </el-button>
            <UploadFilesVue :initConfig="initConfig" @updateFilePaths="handleUpdateFilePaths" :resetFiles="resetFiles"></UploadFilesVue>
            <!-- <el-upload class="upload-demo" v-model:file-list="fileList" action="" multiple="true"
              :http-request="handleUpLoad" :on-success="handleSuccess" :on-error="handleError"
              :on-remove="handleRemove">
              <el-button class="upload-btn" type="primary" plain size="small">上传</el-button>
            </el-upload> -->
          </div>
          <!-- 关联的文件 -->
          <div style="margin-top: 10px;width: 100%;display: flex;flex-direction: column;flex-wrap: wrap;">
            <el-tag
              style="margin-bottom: 5px;display: flex;justify-content: space-between;margin-right: 10px;"
              v-for="(file, index) in newAssFilesList"
              :key="index"
              closable
              :disable-transitions="false"
              @close="handleDelAssFile(file)"
            >
              {{ handleFileName(file).fileName }}
            </el-tag>
          </div>
        </el-form-item>

        <!-- 创建需求 -->
        <el-form-item class="create-button">
          <el-button type="primary" @click="handleResetRequirement">重置</el-button>
          <el-button type="primary" @click="handleCreateRequirement(ruleCreateFormRef)">创建</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 添加项目名称对话框 -->
    <el-dialog id="dialogForm" style="width: 400px; margin-top: 200px" v-model="dialogAddProVisible" title="添加项目"
      :close-on-click-modal="false" :show-close="true" :before-close="handleBeforeCancel">
      <el-input placeholder="请输入项目名称" v-model="newProjectName"></el-input>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleAddProjectDialog">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 关联文件 -->
    <AssRequiremenFileVue v-model:isOpen="openModal" @add-files="handleAddFiles"></AssRequiremenFileVue>
  </div>
</template>

<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { IDomEditor} from '@wangeditor/editor';

import { ref, onMounted, reactive, onBeforeUnmount, shallowRef, computed, nextTick } from "vue";
import type { FormInstance } from 'element-plus';
import { ElMessage, ElMessageBox } from "element-plus";
import useCommonDataStore from "@/store/common/common";
import { postAddItmeItem, postCreateRequirement, GetItemListByUser, } from "@/api/newDemands/index";
import { postUploadFile } from "@/api/common/index";
import { isValidateEditor, handleFileName, fileType } from "@/utils/utils";
import { useRouter } from "vue-router";
import AssRequiremenFileVue from '@/components/requirement/assRequiremenFile.vue';
import useQuickCreateStore from "@/store/common/clipboar";
import EditorMsgVue from "@/components/requirement/editorMsg.vue";
import UploadFilesVue from "@/components/requirement/uploadFiles.vue";


interface AllTypeList {
  id: number;
  type: string;
  bgColor: string;
}
interface AllRoleUserList {
  nickName: string;
  headerImg: string;
  uuid: string;
}
interface CreateRequirementForm {
  projectId: number | null,
  projectType: number | null,
  taskType: number,
  projectTitle: string,
  itemRequirementBossNameUUID: string | null,
  onlineTime: string | null,
  projectMsg: string,
  filePaths: Array<[String]>
}


const loading = ref(false);
let useCommonStore = useCommonDataStore();
// let userStore = useUserStore();
let router = useRouter();
const quickCreateStore = useQuickCreateStore();

//* 上传文件初始配置
const initConfig = {
  tipText: "",// 提示文本
  type: "primary",// 按钮类型
  plain: true,// 按钮样式
  btnText: "上传",// 按钮文本
  fileUrl: "/file/upload_file",// 上传地址
  fileType: "draftPath",// 上传类型
  fileTypeId: "5",// 上传类型id
};
const resetFiles = ref(false);// 是否清除已上传文件列表

const allProjectOptions = ref<any>([]); // 获取所有项目名称下拉列表数据
const allTypeLists = ref<AllTypeList[]>([]); // 定义所有项目名称列表
const allRoleUserList = ref<AllRoleUserList[]>([]); // 定义所有研发人员列表

const dialogAddProVisible = ref(false); //添加项目名称弹窗控件
const newProjectName = ref(""); // 临时存储新项目名称
// const fileList = ref<any>([]);//已上传的附件
const filePaths = ref<any>([]);//所有上传文件响应地址
const isAuthorityId = ref<any>();//当前用户的权限ID

// 初始化任务类型
const allTaskLists = ref<AllTypeList[]>([
  {
    id: 1,
    type: "上线任务",
    bgColor: "#FF6B6B"
  },
  {
    id: 2,
    type: "运维任务",
    bgColor: "#4ECDC4"
  },
  {
    id: 3,
    type: "回归任务",
    bgColor: "#FFD166"
  },
  {
    id: 4,
    type: "日常任务",
    bgColor: "#FFD166"
  }
]);


// 表单实例
const ruleCreateFormRef = ref<FormInstance>();
// 表单数据初始值
const createRequirementForm = reactive<CreateRequirementForm>({
  projectId: null,
  projectType: null,
  taskType: 1,
  projectTitle: "",
  itemRequirementBossNameUUID: "",
  onlineTime: null,
  projectMsg: "",
  filePaths: []
});

// 表单验证规则
const createRules = reactive({
  projectId: [{ required: true, message: "请选择项目名称", trigger: "blur" }],
  projectType: [{ required: true, message: "请选择需求类型", trigger: "blur" }],
  projectTitle: [{ required: true, message: "请输入需求名称", trigger: "blur" }],
  onlineTime: [{ required: true, message: "请选择预计上线时间", trigger: "blur" }],
  itemRequirementBossNameUUID: [{
    required: true,
    message: "请选择审核人",
    trigger: "blur",
  }],
  projectMsg: [{
    required: true,
    message: "请输入需求详情",
    trigger: "blur",
    // @ts-ignore
    validator: (rule: any, value: any, callback: any) => {
      // 调用自定义验证函数
      if (isValidateEditor(value)) {
        callback(new Error("需求详情不能为空格或空行！"));
      } else {
        callback();
      }
    }
  }],
});

const openModal = ref(false);
const newAssFilesList = ref<any>([]);// 新关联的文件


// 获取公共数据
const getCommon = async (index: any) => {
  await useCommonStore.getAllReqTypesList();
  await useCommonStore.getAllProjectList();
  await useCommonStore.getAllRoleUsersList(index);

  isAuthorityId.value = localStorage.getItem("authorityId");

  allTypeLists.value = useCommonStore.$state.allReqTypesList;
  allRoleUserList.value = useCommonStore.$state.allRoleUserList;
};

// TODO 获取项目名称列表数据
const handleProjectOptions = async () => {
  loading.value = true;
  const { data } = await GetItemListByUser();
  if (data.code === 200) {
    allProjectOptions.value = data.data;
    loading.value = false;
  } else {
    ElMessage.error(data.msg);
    return;
  }
};

// TODO 添加项目功能
const handleAddProjectDialog = async () => {
  loading.value = true;

  // 验证newProjectName是否为空
  if (newProjectName.value.trim() === "") {
    alert("请输入项目名称");
    return;
  } else if (
    allProjectOptions.value.some(
      (item: any) => item.itemName === newProjectName.value
    )
  ) {
    alert("该项目已创建，请直接选择！");
    return;
  } else {
    // 发起添加项目请求
    const { data } = await postAddItmeItem({
      itemName: newProjectName.value,
      taskType: createRequirementForm.taskType,
    });
    if (data.code === 200) {
      dialogAddProVisible.value = false;
      ElMessage.success(data.msg);
      await getCommon(777);
      createRequirementForm.projectId = allProjectOptions.value[allProjectOptions.value.length - 1].id;
      loading.value = false;
    } else {
      ElMessage.error(data.msg);
      dialogAddProVisible.value = false;
      loading.value = false;
      throw console.error(data.msg);
    }
  }
};

// 取消/关闭添加项目/需求类型功能
const handleCancel = () => {
  dialogAddProVisible.value = false;
  newProjectName.value = "";
};
const handleBeforeCancel = (done: any) => {
  dialogAddProVisible.value = false;
  newProjectName.value = "";
  done();
};

// 接收子组件中上传的文件地址
const handleUpdateFilePaths = (value: any) => {
  console.log("接收值：", value);
  filePaths.value = value;
  console.log("父组件中的文件：", filePaths.value);
};

// TODO 规定预计上线时间为today及之后，之前的不可选
const disabledDate = (time: any) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return time.getTime() < today.getTime();
};


// TODO 自定义上传文件
// const handleUpLoad = async (options: any) => {
//   console.log("Options:", options);
//   await postUploadFile(options.file, "draftPath", "5").then(res => {
//     options.onSuccess(res);
//   }).catch(error => {
//     options.onError(error);
//   })
// };


// const handleSuccess = (v: any) => {
//   if (v.data.data && v.data.data.resultFilePath) {
//     // @ts-ignore
//     filePaths.value.push(v.data.data);
//   }
// };

// const handleError = (err: any) => {
//   ElMessage.error(err);
// };

// const handleRemove = (v: any) => {
//   fileList.value = fileList.value.filter((item: any) => item.name !== v.name);
//   filePaths.value = filePaths.value.filter((path: any) => path.fileName !== v.name);
// };


// TODO 需求详情-富文本编辑器
const editorRef = shallowRef();
const valueHtml = ref("");// 富文本初始值
const toolbarConfig = { toolbarKeys: ["uploadImage"] };
const editorConfig = {
  placeholder: "请输入内容...",
  showLinkImg: false,
  scroll: true,
  // 上传图片配置
  MENU_CONF: {
    uploadImage: {
      server: "/saferycom/file/upload_file",
      fieldName: "file",
      allowedFileTypes: ["image/*"],
      uploadImgMaxSize: 10 * 1024 * 1024, // 设置图片最大上传大小为10MB
      maxFileSize: 10 * 1024 * 1024, // 设置文件大小限制为10MB
      headers: {
        token: localStorage.getItem("TOKEN"),
      },
      customInsert: async (res: any, insertFn: any) => {
        if (res.code === 200) {
          insertFn(res.data.resultFilePath); //上传到服务器
        } else {
          ElMessage.error("上传图片失败");
          throw new Error();
        }
      },
      customPaste: async (editor: any, event: any) => {
        const items = event.clipboarData.items;
        for (let item of items) {
          if (item.kind === 'file' && item.type.startsWith('image/')) {
            const file = item.getAsFile();
            const formData = new FormData();
            formData.append('file', file);
            fetch("/saferycom/file/upload_file", {
              method: "POST",
              body: formData,
            })
              .then(response => response.json())
              .then(result => {
                editor.cmd.do('insertHtml', `<img src="${result.resultFilePath}"/>`);
              })
              .catch(error => {
                ElMessage.error("粘贴图片上传失败", error);
                event.preventDefault();
              });
          }
        }
        event.preventDefault();
        return false;
      },
    },
  },
};

onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
};

const handleChange = (editor: IDomEditor) => {
  const data = editor.getHtml();

  // 解析HTML字符串为DOM
  const parser = new DOMParser();
  const doc = parser.parseFromString(data, 'text/html');

  // 获取所有的img标签
  const images = doc.querySelectorAll('img');

  // 为每个img标签添加style属性
  images.forEach(img => {
    img.setAttribute('style', 'width: 30%;');
  });

  // 将修改后的DOM转换回字符串
  const modifiedData = doc.body.innerHTML;

  createRequirementForm.projectMsg = modifiedData;
};


// TODO 点击创建需求功能
const handleCreateRequirement = async (formEl: FormInstance | undefined) => {
  loading.value = true;
  console.log("上传文件：", filePaths.value);
  console.log("关联文件：", newAssFilesList.value);

  if ((filePaths.value.length + newAssFilesList.value.length) > 0) {
    // let A = filePaths.value.map((path: any) => path.resultFilePath);
    createRequirementForm.filePaths = [...filePaths.value, ...newAssFilesList.value];
  }
  console.log("请求参数：", createRequirementForm);

  if (!formEl) {
    console.error("表单验证失败，请将内容填写完整");
    return;
  };

  // 表单验证
  const validatePromise = formEl.validate();
  try {
    await validatePromise;
    // 表单验证成功
    await ElMessageBox.confirm("确定要创建需求吗？", "确定", {
      cancelButtonText: "取消",
      confirmButtonText: "确定",
      type: "warning",
    }).then(async () => {
      //* 处理请求参数
      const reqData = {
        projectId: createRequirementForm.projectId,
        projectType: createRequirementForm.projectType,
        projectTitle: createRequirementForm.projectTitle,
        itemRequirementBossNameUUID: createRequirementForm.itemRequirementBossNameUUID,
        // onlineTime: `${createRequirementForm.onlineTime} ${new Date().toLocaleTimeString()}`,
        onlineTime: createRequirementForm.onlineTime,
        projectMsg: createRequirementForm.projectMsg,
        filePaths: createRequirementForm.filePaths,
        taskType: createRequirementForm.taskType
      };

      console.log("待提交数据：", reqData);

      const { data } = await postCreateRequirement(reqData);
      if (data.code === 200) {
        loading.value = false;
        ElMessage.success(data.msg);
        formEl.resetFields();
        filePaths.value = [];
        // fileList.value = [];
        createRequirementForm.filePaths = [];
        loading.value = false;
        router.push("/requirement/userCreate");
      } else {
        loading.value = false;
        ElMessage.error(data.msg);
        throw console.log(data.msg);
      }

    }).catch(async () => {
      console.log("取消创建需求操作！");
      loading.value = false;
    });
  } catch (error) {
    // 表单验证失败
    loading.value = false;
    console.error("表单验证失败，请将内容填写完整");
    return;
  }
};

// TODO 重置需求
const handleResetRequirement = () => {
  // 表单数据初始值
  createRequirementForm.projectId = null;
  createRequirementForm.projectType = null;
  createRequirementForm.taskType = 1;
  createRequirementForm.projectTitle = "";
  createRequirementForm.itemRequirementBossNameUUID = "";
  createRequirementForm.onlineTime = null;
  createRequirementForm.projectMsg = "";
  createRequirementForm.filePaths = [];
  valueHtml.value = "";
  // fileList.value = [];
  filePaths.value = [];
  newAssFilesList.value = [];
  resetFiles.value = true;
  setTimeout(() => {
    resetFiles.value = false;
  }, 100)
};

// TODO　关联文件
// 监听子组件的事件函数，并接收子组件中选中的文件
const handleAddFiles = (data: any) => {
  newAssFilesList.value = newAssFilesList.value.concat(data);
};
// 删除关联文件
const handleDelAssFile = (row: any) => {
  newAssFilesList.value.splice(newAssFilesList.value.indexOf(row), 1);
};
    // 富文本数据更新
const updateMsg = (newValue: any) => {
  createRequirementForm.projectMsg = newValue;
  return createRequirementForm.projectMsg;
};




onMounted(async () => {
  if (quickCreateStore.quickCreateData == null) {
     loading.value = true;
     await getCommon(333);
     await handleProjectOptions();
     
     valueHtml.value = "";
     setTimeout(() => {
       valueHtml.value = "";
     }, 300);
     loading.value = false;
  };

  if (quickCreateStore.quickCreateData) {
    loading.value = true;
    await getCommon(333);
    await handleProjectOptions();
    Object.assign(createRequirementForm, quickCreateStore.quickCreateData);
    console.log("初始数据：", createRequirementForm.projectMsg);
    valueHtml.value = createRequirementForm.projectMsg;
    loading.value = false;
    quickCreateStore.clearQuickCreateData();
  };


  await nextTick();

});
</script>
<style lang="scss" scoped>
.content-container {
  background-color: white;
  display: flex;
  flex-direction: column;
  padding: 10px;

  /* 标题样式 */
  .title-top-box {
    width: 100%;
    height: 40px;
    margin-bottom: 20px;

    .title {
      width: 100%;
      font-size: 24px;
      font-family: Arial, Helvetica, sans-serif;
      border-bottom: 1px solid #dcdfe6;
      color: #000;
    }
  }

  /* 创建需求 */
  .create-box {
    height: 100%;
    overflow: auto;

    .create-form {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;

      .add-icon {
        color: #dcdfe6;
        cursor: pointer;
        margin-left: 5px;
      }

      .add-icon:hover {
        color: #409eff;
      }

      .is-check-role {
        background-color: #409eff;
      }

      .upload-box {
        width: 100%;

        // height: 100px;
        .el-form-item__content {
          align-content: flex-start;
        }
      }
    }

    .create-form>*:not(.create-button) {
      order: 1;
    }

    .create-button {
      order: 2;
      margin-left: auto;
      margin-right: 10px;
      margin-top: 10px;
    }
  }
}
</style>
<style>
.el-upload {
  --el-upload-dragger-padding-horizontal: 0px;

  .el-upload-dragger .el-icon--upload {
    margin-top: 10px;
  }
}

.el-form-item__content {
  align-content: flex-start;
}

.upload-demo {
  align-content: flex-start;
}

.el-form-item__label {
  font-weight: bold;
}

.el-radio-button {
  border-radius: 0;
  margin-right: 10px;
  border: none;
}

.el-radio-button:first-child .el-radio-button__inner,
.el-radio-button:last-child .el-radio-button__inner {
  border-radius: 5px;
}

.el-radio-button .el-radio-button__inner {
  border: 1px solid #dcdfe6;
  border-radius: 5px;
}
</style>
